import {
  getIconComponentName,
  DEFAULT_FORM_LAYOUT,
  KfBackendEnumPicker,
  KfBizQuickFormProps,
  KfFloatingContextProps,
  KfIconPicker,
  KfInput,
  KfInputNumber,
  KfQuickForm,
  KfTextArea,
  KfUpload,
  KfMenuPicker,
} from 'kf-web-library';
import * as API from '@/services';
import { Form } from 'antd';
import type { FunctionComponent } from 'react';
import React from 'react';

const FormItem = Form.Item;
type QueryEntity = API.Menu;
type CreateEntity = API.Menu_Create;
type ModifyEntity = API.Menu_Modify;

type DataFormProps = {} & KfBizQuickFormProps & KfFloatingContextProps;

/**
 * 菜单表单
 */
const QuickForm: FunctionComponent<DataFormProps> = (props) => {
  const { formType, bizId, ...rest } = props;

  return (
    <KfQuickForm
      formType={formType}
      formProps={{
        ...DEFAULT_FORM_LAYOUT,
      }}
      queryRequest={{
        view: true,
        modify: true,
        duplicate: true,
      }}
      defaultQueryRequest={() =>
        API.queryMenu(bizId!).then((resp) => {
          if (resp.flag) {
            resp.data = {
              ...resp.data,
              icon: getIconComponentName(resp.data.icon),
            } as ModifyEntity;
          }
          return new Promise((resolve) => resolve(resp));
        })
      }
      submitRequest={{
        create: (formValues) => API.createMenu({ ...formValues } as CreateEntity),
        modify: (formValues) => API.modifyMenu({ ...formValues, id: bizId } as ModifyEntity),
        duplicate: (formValues) => API.createMenu({ ...formValues } as CreateEntity),
      }}
      {...rest}
    >
      <FormItem name={nameof<ModifyEntity>((x) => x.parentId)} label="上级菜单" rules={[{ required: false }]}>
        <KfMenuPicker.TreeSelect excludeKeys={(bizId && formType === 'modify' ? [bizId] : []) as string[]} />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.icon)} label="菜单图标" rules={[{ required: true }]}>
        <KfIconPicker />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.code)} label="菜单唯一标识" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.name)} label="菜单名称" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.path)} label="菜单路径" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.type)} label="菜单类型" rules={[{ required: true }]}>
        <KfBackendEnumPicker.RadioGroup enumType={'MenuType'} />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.seq)} label="排序号" rules={[{ required: true }]}>
        <KfInputNumber />
      </FormItem>
    </KfQuickForm>
  );
};

export default QuickForm;
